import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import CryptoJS from 'crypto-js'
import LZString from 'lz-string/libs/lz-string'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0,
    name: '嘟嘟',
    list: [
      {
        id: 1,
        name: '测试'
      },
      {
        id: 2,
        name: 'cerf'
      }
    ]
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => {
          const ciphertext = sessionStorage.getItem(key)
          if (import.meta.env.DEV) {
            return ciphertext ? JSON.parse(ciphertext) : null
          } else {
            if (ciphertext) {
              const deCompressedData = LZString.decompressFromUTF16(ciphertext)
              const bytes = CryptoJS.AES.decrypt(deCompressedData, 'secret key 123')
              const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
              return decryptedData
            }
            return ciphertext
          }
        },
        setItem: (key, value) => {
          if (import.meta.env.DEV) {
            sessionStorage.setItem(key, value)
          } else {
            const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(value), 'secret key 123')
              .toString()
            const compressedData = LZString.compressToUTF16(encryptedData)
            sessionStorage.setItem(key, compressedData)
          }
        },
        removeItem: (key) => {
          sessionStorage.removeItem(key)
        }
      }
    })
  ]
})

export default store
